//
//  LSRAdViewController.m
//  BaiSiProject
//
//  Created by lshenrong on 16/7/6.
//  Copyright © 2016年 lshenrong. All rights reserved.
//

#import "LSRAdViewController.h"
#import <AFNetworking.h>
#import <AFHTTPSessionManager.h>
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "LSRTabBarController.h"

#import "LSRAdItem.h"
#define iphone5s (LSRScreenH==568)
#define iphone6s  (LSRScreenH==667)
#define iphone6p (LSRScreenH==736)
#define LSRCode @"phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc8nWbvrjTdQjRvrHb4QWDvnjDdPBuk5yRzPj6sPvRdgvPsTBu_my4bTvP9TARqnam"
@interface LSRAdViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIView *containerView;

@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;
/**模型属性*/
@property(strong,nonatomic  )LSRAdItem *item;

/**定时器*/
@property(strong,nonatomic  )NSTimer *timer;


@end

@implementation LSRAdViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
   
  //设置背景图片
    [self setBgImage];
    
    [self loadData];
    
}

# pragma  mark ----ADJump
- (IBAction)jump:(UIButton *)sender {
    
    //跳转到主控制器，没有到导航控制器，不能用push,modal会强引用上一个控制器，不适合
    
    LSRTabBarController *tabBarVC=[[LSRTabBarController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController=tabBarVC;
    
    //销毁定时器,一旦创建了定时器就要想要不用了的时候要销毁
    [self.timer invalidate];
    
}
-(void)autoJump
{

    static  int i=0;

    i--;

    NSString *title=[NSString stringWithFormat:@"跳转（%d）",i];
    
    [self.jumpBtn setTitle:title forState:UIControlStateNormal];
    
    if (i==-1) {
        
       //跳转到主控制器，调用跳转方法
        [self jump:nil];//没有按钮是可以,是可以传空值过去的
        
    }

}
#pragma mark ---- 设置背景图片，下载广告数据

-(void)setBgImage
{
    NSLog(@"screenW=%f",[UIScreen mainScreen].bounds.size.width);
    if (iphone5s)
    {
        
        self.imageView.image=[UIImage imageNamed:@"LaunchImage-568h"];
    }
    else if (iphone6s)
    {
        self.imageView.image=[UIImage imageNamed:@"LaunchImage-800-667h"];
    
    }
    else if (iphone6p)
    {
        self.imageView.image=[UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
        
    }

   




}

-(void)loadData
{
    
   //请求参数
    NSMutableDictionary *parameter=[NSMutableDictionary dictionary];
    
    parameter[@"code2"]=LSRCode;
    
    //会话申请
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    
  manager.responseSerializer=[AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html", nil];
    //还有一种方式是直接到AFN内部去改，通过跳方法，添加text/html，这种方式的前提是text/html真实类型是json

    
    [manager GET:@"http://mobads.baidu.com/cpro/ui/mads.php" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
//        NSLog(@"%@",responseObject);
        [responseObject writeToFile:@"/Users/lshenrng/Desktop/data/ad.plist" atomically:YES];
        NSDictionary *ADdict=[responseObject[@"ad"] firstObject];
        
        //字典转模型(类方法)
        LSRAdItem *item=[LSRAdItem mj_objectWithKeyValues:ADdict];
        
        self.item=item;
//        NSLog(@"%@",ADdict);
        
        //下载图片
        UIImageView *adImageView=[[UIImageView alloc] init];
        
        [self.containerView addSubview:adImageView];
        //添加广告图片
        [adImageView  sd_setImageWithURL:[NSURL URLWithString:item.w_picurl] ];
        //做一个容错处理、没有图片的时候返回
        if (item.w<=0) {
            
            return ;
        }
        
        
        //设置adImageView]的frame
        CGFloat w=LSRScreenW;
        CGFloat h=w/item.w * item.h;
        
        adImageView.frame=CGRectMake(0, 0, w, h);
        
        //点击图片时候跳转
        //创建点击手势
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        //添加手势 ,添加到containerView不用inter
        [self.containerView addGestureRecognizer:tap];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);

        
    }];


//   NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(autoJump) userInfo:nil repeats:YES];
//    
//    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    //这个方法不需要加入到主循环
    NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(autoJump) userInfo:nil repeats:YES];
    
    self.timer=timer;
    

}
-(void)tap
{

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.item.ori_curl]];

}



#pragma  mark ---- dataSource



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
